# -*- coding: utf-8 -*-
from api import api, GlobalError, ERROR_ARTICLE
from flask import jsonify, request
from model.article import Article
from model.studio import Studio
from werkzeug.exceptions import NotFound
from util.removeNBSP import removeNBSP
import re


@api.route('/article/<article_id>', methods=['GET'])
def get_article(article_id):
    '''
## 获取文章详情

    GET /api/article/<article_id>

Parameters:
* `b_web` (boolean, optional)-如果为真，表示是B端的请求，要保留&nbsp，去除<brief>；app端的需要去除&nbsp，保留<brief>

Return:

* `articleId` (string)
* `content` (string)
* `createTime` (long)
* `images` (list of string)
* `studioId` (string)
* `title` (string)
* `viewNum` (int) - 被点击次数
    '''
    try:
        article = Article.get({
            Article.Field._id: article_id
        })
    except NotFound:
        return jsonify(stat=0, **GlobalError.INVALID_ARTICLE_ID), 403

    article.data['articleId'] = article_id
    article.update({
        '$inc': {
            Article.Field.viewNum: 1
        }
    })
    del article.data[Article.Field._id]
    try:
        studio = Studio.get({
            Studio.Field._id: article.data.get(Article.Field.studioId, '')
        })
    except NotFound:
        return jsonify(stat=0, **GlobalError.INVALID_ARTICLE_ID), 403
    article.data['studioName'] = studio.data.get(Studio.Field.name)
    article.data['studioAvatarUrl'] = studio.data.get(Studio.Field.avatarUrl)

    b_web = request.args.get('b_web', None)
    article.data[Article.Field.content] = removeNBSP(article.data[Article.Field.content], b_web)

    return jsonify(stat=1, article=article.data)


@api.route('/articles', methods=['GET'])
def get_all_article():
    '''
## 分页获取首页文章

    GET /api/articles

Parameters:

* `city` (string, optional)
* `sort` (int, required) - 0 表示按照时间排序，1 表示按照热度排序，默认为 0
* `skip` (int, required) - 跳过多少文章，默认为 0
* `total` (int, required) - 一次返回多少，默认为 p20
* `timestamp` (long, optional) - 返回这个时间戳之前的文章
* `b_web` (boolean, optional)-如果为真，表示是B端的请求，要保留&nbsp，去除<brief>；app端的需要去除&nbsp，保留<brief>
    '''
    city = request.args.get('city', None)
    sort_way = request.args.get('sort', 0, type=int)
    sort_field = [Article.Field.createTime, Article.Field.viewNum]
    skip = request.args.get('skip', 0, type=int)
    total = request.args.get('total', 20, type=int)
    timestamp = request.args.get('timestamp', -1, type=long)
    b_web = request.args.get('b_web', None)

    query_condition = {}
    if timestamp != -1:
        query_condition[Article.Field.createTime] = {'$lt': timestamp}
        skip = 0

    if city:
        article_list = Article.find(query_condition,
                                    sort=[(sort_field[sort_way], -1)])
    else:
        article_list = Article.find(query_condition,
                                    sort=[(sort_field[sort_way], -1)],
                                    skip=skip,
                                    limit=total)

    articles = []
    for article in article_list:
        article['articleId'] = article[Article.Field._id]
        del article[Article.Field._id]
        try:
            studio = Studio.get({
                Studio.Field._id: article[Article.Field.studioId]
            }, [
                Studio.Field.name,
                Studio.Field.avatarUrl,
                Studio.Field.place
            ])
            if city and studio.data.get(Studio.Field.place).get(Studio.Place.city) != city:
                continue
        except NotFound:
            continue
        article['studioName'] = studio.data.get(Studio.Field.name)
        article['studioAvatarUrl'] = studio.data.get(Studio.Field.avatarUrl)
        article[Article.Field.content] = removeNBSP(article[Article.Field.content], b_web)
        articles.append(article)
    if city:
        articles = articles[skip:skip + total]

    return jsonify(stat=1, articles=articles)
